package gui.polish;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JEditorPane;

import java.awt.Panel;
import java.awt.Button;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import JFlex.ErrorMessages;
import clients.RPCClient;
import entities.StartPolishEntity;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.lang.reflect.Array;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Scanner;
import java.util.jar.JarInputStream;
import java.awt.event.ActionEvent;

import javax.swing.JList;
import javax.swing.AbstractListModel;
import javax.swing.JScrollPane;
import javax.swing.JLayeredPane;

import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Font;

import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;

import java.awt.ScrollPane;

import javax.swing.JComboBox;
import javax.swing.JCheckBox;
import javax.swing.JRadioButton;

import org.apache.poi.hslf.model.Table;
import org.apache.poi.ss.formula.functions.Days360;

import utilities.Services;

import javax.swing.JOptionPane;

import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;

import net.miginfocom.swing.MigLayout;

import java.awt.SystemColor;

import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
/**
 * 
 * @author adam
 * This panel is the second main panel in polish GUI , here the user can see the orders that came from earlier stages , and initialize them in a polish phase into a jar .
 */
public class StartPolishPanel extends javax.swing.JPanel {
	private JTextField textField;
	private JTextField jtf_pelletsCycles;
	private StartPolishPanel myStartPolish ;
	private PolishFrame myFrame;
	private PolishPanel myPolishPanel;
	private RPCClient StartPolishClient;
	private JTextField jtf_topline;
	private JTextField jtf_totalDays;
	private JTextField jtf_endDate;
	private JTable table_1;
	private JComboBox jarIDcomboBox;
	private JComboBox orderIDComboBox;
	private String topline;
	private String daysOfPolish;
	private ArrayList<String> myArray , myArrayRemoved,myOldArray;  // Holds the added \ removed orderId's 
	private int i=0,row; // row will hold the row number , i is a corelated index that will be increased\decreased depends on if we add or remove orderID from myArray and myArrayRemoved
	private String selectedRow;
	private DefaultTableModel model1 ;
	private int rowCount ; // variable that holds the number of orderID's after clicking the right jar the very first time .
	private short flag =0; //Holding the information that will let us know if i will increase or not , will change to 1 when first time initializing the add screen .
	//private short addRemoveAcc=0;	// Holds the flag if there were any change in adding or removing oredrsID 
	private OrderIDSearchPanel myOrderIDSerchPanel;
	private StartNewPolishSerachFrame mySearchFrame;
	private Boolean isToplineButtonEditable = true;
	private Boolean isTotalDaysEditable = true;
	private JButton btn_accept;
	private JButton btn_addOrderID;
	private JButton btn_removeOrderID;
	private JTextPane textPaneComments;
	private int newPolish=0;
/**
 * Constructor
 * @param myFrame
 * @param myPolishPanel
 * @throws Exception
 */
	public StartPolishPanel(PolishFrame myFrame, PolishPanel myPolishPanel) throws Exception {
		setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "\u05D4\u05D5\u05E1\u05E4\u05EA \u05DC\u05D9\u05D8\u05D5\u05E9", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0)));
		setBackground(new Color(173, 216, 230));
		try {
			StartPolishClient= new RPCClient();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		setLayout(new MigLayout("", "[grow][100px][3px][46px][4px][47px][55px][25px][12px][2px][80px][68px][grow]", "[grow][14px][28px][28px][4px][25px][6px][25px][9px][25px][4px][14px][4px][45px][][23px][grow]"));
		
		JLabel label_1 = new JLabel("צנצנת");
		label_1.setFont(new Font("Tahoma", Font.PLAIN, 13));
		label_1.setHorizontalAlignment(SwingConstants.CENTER);
		add(label_1, "cell 11 2,alignx center,aligny top");
		
		JLabel label_2 = new JLabel("פק\"ע");
		label_2.setFont(new Font("Tahoma", Font.PLAIN, 13));
		label_2.setHorizontalAlignment(SwingConstants.CENTER);
		add(label_2, "cell 11 3,alignx center,aligny center");
		
		JLabel lblTopline = new JLabel("Topline");
		lblTopline.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblTopline.setHorizontalAlignment(SwingConstants.CENTER);
		add(lblTopline, "cell 11 5,alignx left,aligny center");
		
		JLabel label_3 = new JLabel("ימי ליטוש");
		label_3.setFont(new Font("Tahoma", Font.PLAIN, 13));
		label_3.setHorizontalAlignment(SwingConstants.CENTER);
		add(label_3, "cell 11 7,alignx left,aligny center");
		
		JLabel label_4 = new JLabel("תאריך סיום");
		label_4.setFont(new Font("Tahoma", Font.PLAIN, 13));
		label_4.setHorizontalAlignment(SwingConstants.CENTER);
		add(label_4, "cell 11 9,growx,aligny center");
		myArray = new ArrayList<String>();
		myArrayRemoved = new ArrayList<String>();
		myOldArray = new ArrayList<String>();
		btn_addOrderID = new JButton("הוסף");
		btn_addOrderID.setFont(new Font("Tahoma", Font.PLAIN, 13));
		btn_addOrderID.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if((jtf_topline.getText().equals("")) || (jtf_topline.getText().equals("שדה חובה")) || (jtf_totalDays.getText().equals(""))|| (jtf_totalDays.getText().equals("שדה חובה"))   ||(orderIDComboBox.getSelectedItem()==null) || (jarIDcomboBox.getSelectedItem()==null) )
				{
					JOptionPane.showMessageDialog(myPolishPanel,
						" שדות לא מלאים.","שגיאה",JOptionPane.ERROR_MESSAGE);
					
				}
				else
				{
//						addRemoveAcc=1;
						selectedRow = orderIDComboBox.getSelectedItem().toString();
						//Start removing the orderId from the comboBox
						myArrayRemoved.add(selectedRow);
						orderIDComboBox.removeItem(orderIDComboBox.getSelectedItem());
						myArray.add(selectedRow);
						//End : removing the orderID from the comboBox
						try{
							int index  = myArray.size()-1;
							String str = myArray.get(index);
							model1.addRow(new Object[]{str});	//Adding the orderID to the table
						}catch(Exception e)
						{
							//e.printStackTrace();
							System.out.printf("i is :",i);
						}
							jtf_topline.setEditable(false);
							jtf_totalDays.setEditable(false);
							isToplineButtonEditable=false;
							isTotalDaysEditable=false;
				}
			}
		});
		btn_addOrderID.setIcon(new ImageIcon(StartPolishPanel.class.getResource("/graphics/createOrder24.png")));
		add(btn_addOrderID, "cell 6 3 3 1,grow");
		
		JLabel label_5 = new JLabel("מחזור כדוריות");
		label_5.setFont(new Font("Tahoma", Font.PLAIN, 13));
		label_5.setHorizontalAlignment(SwingConstants.CENTER);
		add(label_5, "cell 6 2 3 1,growx,aligny center");
		
		jtf_pelletsCycles = new JTextField();
		jtf_pelletsCycles.setEditable(false);
		jtf_pelletsCycles.setForeground(Color.BLACK);
		jtf_pelletsCycles.setHorizontalAlignment(SwingConstants.CENTER);
		jtf_pelletsCycles.setColumns(10);
		add(jtf_pelletsCycles, "cell 5 2,grow");
		
		JButton btn_changePelletes = new JButton("החלפת כדוריות");
		btn_changePelletes.setFont(new Font("Tahoma", Font.PLAIN, 13));
		btn_changePelletes.setIcon(new ImageIcon(StartPolishPanel.class.getResource("/graphics/replacePellets.png")));
		btn_changePelletes.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(jarIDcomboBox.getSelectedItem()!=null)
				{
					Object[] options = {"כן","לא"};
					int answer = JOptionPane.showOptionDialog(myPolishPanel, "האם אתה בטוח שברצונך להחליף את הכדוריות ? הדבר יגרור איפוס ערכם", "החלפת כדוריות", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[1]);
					if(answer==0)
					{
						ArrayList<Object>message = new ArrayList<>();
						ArrayList<Object>respond = new ArrayList<>();
						message.add("replacePellets");
						message.add(jarIDcomboBox.getSelectedItem().toString());
						try{
							StartPolishClient = new RPCClient();
							respond = StartPolishClient.call(message);
							jtf_pelletsCycles.setText("0");
						}catch(Exception e)
						{
							//e.printStackTrace();
						//	//System.out.println("ERROR -> StartPolishPanel ->ActionListener btn_ChangePellets");
							System.exit(0);
						}
					}else{}
				}
				else JOptionPane.showMessageDialog(myPolishPanel, "יש לבחור צנצנת טרם הלחיצה על הכפתור", "שגיאה", JOptionPane.ERROR_MESSAGE);
			}
		});
		add(btn_changePelletes, "cell 1 2,alignx right,aligny top");
		
		JLabel label_6 = new JLabel("פק\"עות בצנצנת:");
		label_6.setFont(new Font("Tahoma", Font.PLAIN, 13));
		add(label_6, "cell 3 3 3 1,alignx right,aligny bottom");
		
		btn_removeOrderID = new JButton("הסר");
		btn_removeOrderID.setFont(new Font("Tahoma", Font.PLAIN, 13));
		btn_removeOrderID.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String daysOfPolis = null;
				String toplin = null;
				String jarID = null;
				String orderID;
				int check;
				check = table_1.getSelectedRow();
				if(check == -1) // checks if nothing is slected in the table (table_1)
				{
					JOptionPane.showMessageDialog(myPolishPanel,
							" יש לבחור פק''ע להסרה.","שגיאה",JOptionPane.ERROR_MESSAGE);
				}
				else
				{
//					addRemoveAcc=1;
					selectedRow = new String ( (String)model1.getValueAt(row,0));
					model1.removeRow(row);
					if(myArray.contains(selectedRow))
					{
						myArray.remove(selectedRow);
								if(myArrayRemoved.contains(selectedRow))
								{
									myArrayRemoved.remove(selectedRow);
									orderIDComboBox.addItem(selectedRow);
								}
					}
					if(table_1.getRowCount() < 1)
					{
						jtf_topline.setEditable(true);
						jtf_totalDays.setEditable(true);
					}
				}
			}
		});
		btn_removeOrderID.setIcon(new ImageIcon(StartPolishPanel.class.getResource("/graphics/delete24.png")));
		add(btn_removeOrderID, "cell 3 13 3 1,alignx left,aligny center");
		
		btn_accept = new JButton("בצע");
		btn_accept.setFont(new Font("Tahoma", Font.PLAIN, 13));
		btn_accept.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
						Iterator itr = myArray.iterator();
						ArrayList<Object> listToAdd = new ArrayList<Object>();
						ArrayList<Object> listToRemove = new ArrayList<Object>();
						if(daysOfPolish==null || topline == null || daysOfPolish.equals("") || daysOfPolish.equals("שדות חובה") || topline.equals("") || topline.equals("שדות חובה"))
						{
							JOptionPane.showMessageDialog(myPolishPanel,
									" יש למלא את כל השדות.","שגיאה",JOptionPane.ERROR_MESSAGE);
						}
						else{
								while(itr.hasNext())
								{
									String str = itr.next().toString();
									if (!myOldArray.contains(str))
										listToAdd.add(str);
								}
								itr = myOldArray.iterator();
								while(itr.hasNext())
								{
									String str = itr.next().toString();
									if(!myArray.contains(str))
										listToRemove.add(str);
								}
								Iterator itr1 = listToAdd.iterator();
								//Start : Local Vars decliration
								String jarID;
								String orderID;
								String toplin;
								String daysOfPolis;
								String comments ;
								//End : local Vars decliration
								jarID = jarIDcomboBox.getSelectedItem().toString();
								toplin = topline;
								daysOfPolis = daysOfPolish;
								comments = textPaneComments.getText().toString();
								ArrayList<Object> message = new ArrayList<Object>();
								ArrayList<Object> respond = new ArrayList<Object>();
							
							while (itr1.hasNext())
							{
								message.add("addNewPolish");
								message.add(jarID);
								orderID = itr1.next().toString(); // takes the orderId from the itr (iterator) that runs on myArray
								message.add(orderID);
								message.add(daysOfPolis);
								message.add(toplin);
								message.add(comments);
								try {
									respond=StartPolishClient.call(message);
								} catch (Exception e) {
									// TODO Auto-generated catch block
									//System.out.println("StartPolishPanel GUI error - couldnt add new Polish to DB ");
								}
								if (respond.get(1).equals("unvalid"))
								{
									JOptionPane.showMessageDialog(myPolishPanel,
											"הפקע שנבחרה '"+ respond.get(2).toString()+"'כבר נמצאת בליטוש" ,"שגיאה",JOptionPane.ERROR_MESSAGE);
							
								}
								else 
								{
									JOptionPane.showMessageDialog(myPolishPanel,
											"הפקע הוספה בהצלחה","אישור",JOptionPane.INFORMATION_MESSAGE);
									setVariables();
									initializeOrderIDComboBox();
								}
								message.clear();
								respond.clear();
							}
							//Updating Pellets cycles , increasing it by one since we started a new polish jar.
							if(listToAdd.size()>0 &&  newPolish!=0)
							{
								newPolish=0;
								ArrayList<Object>messageUpdateCycles = new ArrayList<>();
								ArrayList<Object>respondUpdateCycles = new ArrayList<>();
								messageUpdateCycles.add("getPelletsCyclesNumber");
								messageUpdateCycles.add(jarID);
								try{
									//Getting the cycles number.
									respondUpdateCycles=StartPolishClient.call(messageUpdateCycles);
									if(respondUpdateCycles.get(1).toString().equalsIgnoreCase("valid"))
									{
										try{
											ArrayList<Object>message1 = new ArrayList<>();
											ArrayList<Object>respond1 = new ArrayList<>();
											message1.add("updatePelletsCycles");
											message1.add(jarID);
											message1.add(respondUpdateCycles.get(2).toString());
											respond1 = StartPolishClient.call(message1);
											setVariables();
											initializeOrderIDComboBox();
										}catch(Exception e12){
											e12.printStackTrace();
											//System.out.println("ERROR - src->gui.polish->StartPolishPanel-> btn_accept.addActionListener(new ActionListener()...(2)");
										}
									}
								}catch(Exception e11){
									e11.printStackTrace();
									//System.out.println("ERROR - src->gui.polish->StartPolishPanel-> btn_accept.addActionListener(new ActionListener()...(1)");
								}
							}
							Iterator itr2 = listToRemove.iterator();
							while(itr2.hasNext())
							{
								String orderIdToRemove = itr2.next().toString();
								String jarIDToRemove = jarIDcomboBox.getSelectedItem().toString();
								message.clear();
								message.add("removeFromPolish");
								message.add(jarIDToRemove);
								message.add(orderIdToRemove);
								try
								{
									respond.clear();
									respond  = StartPolishClient.call(message);
								}
								catch(Exception e)
								{
									JOptionPane.showMessageDialog(myPolishPanel,
											  "שגיאה בבסיס הנתונים, לא ניתן להסיר את פק''ע \n" + orderIdToRemove,"שגיאה",JOptionPane.ERROR_MESSAGE);
									
								}
								if (respond.get(1).equals("unvalid"))
								{
									JOptionPane.showMessageDialog(myPolishPanel,
											  "הפק''ע הוסרה בהצלחה." ,"אישור",JOptionPane.INFORMATION_MESSAGE);
								}
								else{
									setVariables();
									initializeOrderIDComboBox();
								}
								message.clear();
								respond.clear();
							}
						}
						if(table_1.getRowCount() < 1)
						{
							jtf_topline.setEditable(true);
							jtf_totalDays.setEditable(true);
						}
			}
		});
		btn_accept.setIcon(new ImageIcon(StartPolishPanel.class.getResource("/graphics/apply.png")));
		add(btn_accept, "cell 10 15 2 1,grow");
		
		JButton btnCancel = new JButton("חזרה");
		btnCancel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				myFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
				ArrayList<Object> message = new ArrayList<>();
				ArrayList<Object> respond=null;
				message.add("initializePolishPane");
				try{
					respond = StartPolishClient.call(message);
				}
				catch (Exception e1)
				{
					e1.printStackTrace();
				}
				myPolishPanel.setVariables(respond);
				myFrame.setContentPane(myPolishPanel);
			}
		});
		btnCancel.setIcon(new ImageIcon(StartPolishPanel.class.getResource("/graphics/back.png")));
		add(btnCancel, "cell 1 15,grow");
		
		
		
		
		this.myFrame=myFrame;
		this.myPolishPanel=myPolishPanel;
		this.myStartPolish=this;
		
		jtf_topline = new JTextField();
		jtf_topline.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				jtf_totalDays.requestFocus();
			}
		});
		jtf_topline.setHorizontalAlignment(SwingConstants.CENTER);
		jtf_topline.setForeground(Color.RED);
		jtf_topline.setText("שדה חובה");
		jtf_topline.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent arg0) {
				Boolean answer = Services.isNumeric(jtf_topline.getText().toString());
				if(answer)
				topline = jtf_topline.getText();
				else
				{
					JOptionPane.showMessageDialog(myPolishPanel,
							  "הוזן ערך שגוי"  ,"שגיאה",JOptionPane.ERROR_MESSAGE);
					jtf_topline.setText("");
				}
				
			}
			@Override
			public void focusGained(FocusEvent e) {
				if(isToplineButtonEditable==true)
				{
					jtf_topline.setText("");
					jtf_topline.setForeground(Color.black);
				}
			}
		});
		jtf_topline.setColumns(10);
		add(jtf_topline, "cell 10 5,grow");
		
		jtf_totalDays = new JTextField();
		jtf_totalDays.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) 
			{
				btn_addOrderID.requestFocus();
			}
		});
		jtf_totalDays.addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent arg0) {
				if((!jtf_totalDays.getText().equals("")) && (!jtf_totalDays.getText().equals("שדה חובה")) && (jtf_totalDays.getText()!=null) )
				{
					int day = Integer.valueOf((jtf_totalDays.getText().toString()));
					Calendar cal = Calendar.getInstance();
					cal.add(Calendar.DATE, day);
					Date date = new Date(cal.getTimeInMillis());
					jtf_endDate.setText(date.toString());
				}
				
			}
		});
		jtf_totalDays.setText("שדה חובה");
		jtf_totalDays.setForeground(Color.RED);
		jtf_totalDays.setHorizontalAlignment(SwingConstants.CENTER);
		jtf_totalDays.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent e) {
				Boolean answer = Services.isNumeric(jtf_totalDays.getText().toString());
				if(answer)
				{
						daysOfPolish = jtf_totalDays.getText();
					if((!jtf_totalDays.getText().equals("")) && (!jtf_totalDays.getText().equals("שדה חובה")) && (jtf_totalDays.getText()!=null) )
					{
						int day = Integer.valueOf(jtf_totalDays.getText());
						Calendar cal = Calendar.getInstance();
						cal.add(Calendar.DATE, day);
						Date date = new Date(cal.getTimeInMillis());
						jtf_endDate.setText(date.toString());
					}
				}
				else
				{
					JOptionPane.showMessageDialog(myPolishPanel,
							  "הוזן ערך שגוי"  ,"שגיאה",JOptionPane.ERROR_MESSAGE);
					jtf_totalDays.setText("");
				}
			}
			@Override
			public void focusGained(FocusEvent e) {
				if(isTotalDaysEditable==true)
				{
					jtf_totalDays.setText("");
					jtf_totalDays.setForeground(Color.black);
				}
			}
		});
		jtf_totalDays.setColumns(10);
		add(jtf_totalDays, "cell 10 7,grow");
		
		jtf_endDate = new JTextField();
		jtf_endDate.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent e) {
				jtf_endDate.setEditable(false);
				jtf_endDate.setForeground(Color.black);
			}
		});
		jtf_endDate.setHorizontalAlignment(SwingConstants.CENTER);
		jtf_endDate.setText("YYYY-MM-DD");
		jtf_endDate.setColumns(10);
		add(jtf_endDate, "cell 8 9 3 1,grow");
		
		JScrollPane scrollPane = new JScrollPane();
		add(scrollPane, "cell 1 3 1 11,grow");
		
		JPanel panel = new JPanel();
		scrollPane.setViewportView(panel);
		
		table_1 = new JTable();
		table_1.setFont(new Font("Tahoma", Font.PLAIN, 15));
		table_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				//Start : returns the index of the orderID selected in table
				row = table_1.convertRowIndexToModel(table_1.getSelectedRow());
				 //System.out.println(row);
				//End :returns the index of the orderID selected in table
			}
		});
		table_1.setAutoCreateRowSorter(true);
		table_1.addKeyListener(new KeyAdapter() {
		});
		table_1.addFocusListener(new FocusAdapter() {
		});
		panel.add(table_1);
		table_1.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"New column"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		table_1.getColumnModel().getColumn(0).setResizable(false);
		model1 = (DefaultTableModel) table_1.getModel();
		
		jarIDcomboBox = new JComboBox();
		jarIDcomboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				//Clearing the textFields from earlier clicks.
				daysOfPolish=jtf_totalDays.getText().toString();
				topline=jtf_topline.getText().toString();
				//myArray.clear();
				i=0;
				setVariables();
				if((!jtf_totalDays.getText().equals("")) && (!jtf_totalDays.getText().equals("שדות חובה")) && !(jtf_totalDays.getText()!=null) )
				{
					int day = Integer.parseInt(jtf_totalDays.getText().toString());
					Calendar cal = Calendar.getInstance();
					cal.add(Calendar.DATE, day);
					Date date = new Date(cal.getTimeInMillis());
					jtf_endDate.setText(date.toString());
					if(table_1.getRowCount() < 1)
					{
						jtf_topline.setEditable(true);
						jtf_totalDays.setEditable(true);
					}
				}
			
			}
		});
		add(jarIDcomboBox, "cell 10 2,growx,aligny top");
		
		orderIDComboBox = new JComboBox();
		add(orderIDComboBox, "cell 10 3,growx,aligny top");
		
		JButton button = new JButton("חיפוש פק\"ע");
		button.setIcon(new ImageIcon(StartPolishPanel.class.getResource("/graphics/search24.png")));
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				mySearchFrame = new StartNewPolishSerachFrame(myFrame);
				
			}
		});
		button.setFont(new Font("Tahoma", Font.PLAIN, 11));
		button.setHorizontalAlignment(SwingConstants.RIGHT);
		add(button, "cell 6 5 3 1,alignx right,aligny top");
		
		JLabel label_7 = new JLabel("הערה:");
		label_7.setFont(new Font("Tahoma", Font.PLAIN, 13));
		label_7.setHorizontalAlignment(SwingConstants.LEFT);
		add(label_7, "cell 11 11,alignx left,aligny top");
		
		JScrollPane scrollPane_1 = new JScrollPane();
		add(scrollPane_1, "cell 6 11 5 3,grow");
		
		textPaneComments = new JTextPane();
		scrollPane_1.setViewportView(textPaneComments);
		textPaneComments.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		initializeOrderIDComboBox();
		ArrayList<Object> comboBoxMessage = new ArrayList<>();
		ArrayList<Object> comboBoxRespond = new ArrayList<>();
		comboBoxMessage.add("initializeComboJarIDBox");
		// initializing combo box jarsID call
		comboBoxRespond=PolishFrame.PolishClient.call(comboBoxMessage);
		// Initialize start polish 
		if(comboBoxRespond.get(1).equals("unvalid"))
		{
			//System.out.println("Unable to retrive Jar's ID ...");
		}
		else setVariablesJarIds(comboBoxRespond);
		
	
	}
	/**
	 *  Initializeing orderID combo box function
	 */
	private void initializeOrderIDComboBox() {
		orderIDComboBox.removeAllItems();
		ArrayList<Object> message = new ArrayList<>();
		message.add("initializeOrderIDComboBox");
		ArrayList<Object> respond1 = new ArrayList<>();
		try{
			respond1 = StartPolishClient.call(message);
		}
		catch (Exception e){
			//System.out.println(e);
		}
		if(respond1.get(1).toString().equals("unvalid"))
		{
			//System.out.println("StartPolishPanel GUI Error - couldnt retrive OrderId's from Database");
		}
		else{
			int j=0;
			while(j+2<respond1.size())
			{
				orderIDComboBox.insertItemAt(respond1.get(j+2),j);
				j++;
			}
		}
	}
	/**
	 * initializing JarID combo box function 
	 * @param comboBoxRespond
	 */
	private void setVariablesJarIds(ArrayList<Object> comboBoxRespond) {
		// TODO Auto-generated method stub
		ArrayList<Object> message = new ArrayList<>();
		int j=0;
		message=comboBoxRespond;
		while(j+2<message.size())
		{
			jarIDcomboBox.insertItemAt(message.get(j+2),j);
			j++;
		}
		
	}
	/**
	 * Sets the variables in place in StartPolishPanel (topline , totaldays , orderID)
	 */
	protected void setVariables() {
		// TODO Auto-generated method stub
		int j=0;
		myArray.clear();
		myArrayRemoved.clear();
		//Clears the table from non relative orderID's 
		model1.setRowCount(0);	
		ArrayList<Object> message = new ArrayList<>();
		ArrayList<Object> respond=null;
		message.add("initializeStartPolish");
		message.add(jarIDcomboBox.getSelectedItem().toString());
		try{
			respond = StartPolishClient.call(message);
			if(respond.get(1).toString().equals("valid"))
			{
				while (j+2<respond.size())
				{
					StartPolishEntity myEntit= (StartPolishEntity) respond.get(2+j);
					model1.addRow(new Object[]{myEntit.getOrderID()});
					myArray.add(myEntit.getOrderID()); // adding to myArray every orderID that is relavant to the jarID selected .
					myArrayRemoved.add(myEntit.getOrderID());
					jtf_topline.setText(myEntit.getTopline());
					topline=myEntit.getTopline();
					jtf_pelletsCycles.setText(myEntit.getPelletesCycles());
					int pelletsCyclesINT = Integer.valueOf(jtf_pelletsCycles.getText().toString()); // number of pellets
					if(pelletsCyclesINT >=25)
					{
						Object[] options = {"כן" , "לא"};
						int answer =JOptionPane.showOptionDialog(myFrame, "יש צורך בהחלפת כדוריות בצנצנת , האם ברצונך להחליף כעת ?", "החלפת כדוריות", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
						if(answer==0)
						{
							StartPolishClient = new RPCClient();
							ArrayList<Object>message1 = new ArrayList<>();
							ArrayList<Object>respond1 = new ArrayList<>();
							message1.add("replacePellets");
							message1.add(jarIDcomboBox.getSelectedItem().toString());
							try{
								respond1 = StartPolishClient.call(message1);
								if(respond1.get(1).toString().equals("valid"))
								{
									jtf_pelletsCycles.setText("0");
								}
							}catch(Exception e)
							{
								//e.printStackTrace();
							//	//System.out.println("ERROR -> StartPolishPanel -> setVariables()");
								System.exit(0);
							}
						}else{}
					}
						btn_accept.setEnabled(true);
						btn_addOrderID.setEnabled(true);
						btn_removeOrderID.setEnabled(true);
					String myString;
					myString=String.valueOf(myEntit.getTotalDays());
					jtf_totalDays.setText(myString);
					daysOfPolish=myString;
					jtf_endDate.setText(myEntit.getEndDate().toString());
					j++;	
				}
				jtf_topline.setEditable(false);
				jtf_totalDays.setEditable(false);
				isTotalDaysEditable=false;
				isToplineButtonEditable=false;
				// setting the Total_days textField
				
			}
			else {
				JOptionPane.showMessageDialog(myPolishPanel,"הצנצנת ריקה","ח.נ.י.ת", JOptionPane.INFORMATION_MESSAGE);
				newPolish=1;
				try{
					// Get jar pelletscycles 
					ArrayList<Object>message2 = new ArrayList<>();
					ArrayList<Object>respond2 = new ArrayList<>();
					message2.add("getPelletsCyclesNumber");
					message2.add(jarIDcomboBox.getSelectedItem().toString());
					respond2 = StartPolishClient.call(message2);
					if(respond2.get(1).toString().equals("valid"))
					{
						jtf_pelletsCycles.setText(respond2.get(2).toString());
					}
					else
						jtf_pelletsCycles.setText("0");
				}
				catch(Exception e)
				{
					//e.printStackTrace();
					System.out.print("ERROR - src-> gui.polish -> StartPolishPanel -> setVariables() ->  couldnt get jar pellets");
				}
				
				jtf_topline.setText("");
				jtf_totalDays.setText("");
				jtf_endDate.setText("YYYY-MM-DD");
				jtf_topline.setEditable(true);
				isToplineButtonEditable=true;
				jtf_totalDays.setEditable(true);
				isTotalDaysEditable=true;
			}
			initializeStartingJarOrders();
		}
		catch (Exception e)
		{
			//System.out.println(e);
		}
		
		
	}
	/**
	 * This method initializes the starting jar orders
	 */
	private void initializeStartingJarOrders() {
		// TODO Auto-generated method stub
		myOldArray.clear();
		String selectedRow;
		int k; 	//number of rows in table 
		rowCount=model1.getRowCount();
		
		for (k =0 ; k<rowCount ; k++)
		{
			selectedRow = new String ( (String)model1.getValueAt(k,0));
			myOldArray.add(selectedRow);
		}
	}
	
	@Override
	public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Color color1 = getBackground();
    Color color2 = color1.darker();
    int w = getWidth();
    int h = getHeight(); 
    GradientPaint gp = new GradientPaint(
            0, 0, color1,
            0, h, color2);

    g2d.setPaint(gp);
    g2d.fillRect(0, 0, w, h);
    }
}
